package cn.com.dstz.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;

import cn.com.dstz.web.constants.Constants;



public final class FileUtils {
	
	private static final Logger logger = Logger.getLogger ( FileUtils.class );
	
	public static boolean writeFile(File file, String content) {
		return writeFile(file.getPath(), content, false);
	}

	
	public static boolean writeFile(String filePath, String content) {
		return writeFile(filePath, content, false);
	}

	
	public static boolean writeFile(String filePath, String content, boolean append) {
		try {
			File file = new File(filePath);
			FileOutputStream out = new FileOutputStream(file, append);
			OutputStreamWriter fwout = new OutputStreamWriter(out, Constants.CHAR_SET);
			BufferedWriter bw = new BufferedWriter(fwout);
			FileLock fl = out.getChannel().tryLock();
			if (fl.isValid()) {
				bw.write(content);
				fl.release();
			}
			bw.flush();
			fwout.flush();
			out.flush();
			bw.close();
			fwout.close();
			out.close();
			bw = null;
			fwout = null;
			out = null;
			return true;
		} catch (IOException e) {
			logger.error ( "写入文件失败 [com.ice.util.FileUtils writeFile(writeFile(String filePath, String content, boolean append))]", e );
		}
		return false;
	}

	public static boolean writeFile(String filePath, String content, int off, int len) {
		File file = new File(filePath);
		if (file.exists()) {
			FileOutputStream outputStream = null;
			OutputStreamWriter outputWriter = null;
			BufferedWriter bufWriter = null;
			try {
				outputStream = new FileOutputStream(filePath);
				outputWriter = new OutputStreamWriter(outputStream, Constants.CHAR_SET);
				bufWriter = new BufferedWriter(outputWriter);
				FileLock fl = outputStream.getChannel().tryLock();
				if (fl.isValid()) {
					bufWriter.write(content, off, len);
					fl.release();
				}
				return true;
			} catch (IOException e) {
				logger.error ( "写入文件失败 [com.ice.util.FileUtils writeFile(String filePath, String content, int off, int len)]", e );
			} finally {
				try {
					bufWriter.close();
					outputWriter.close();
					outputStream.close();
				} catch (IOException e) {
					logger.error ( "关闭流失败 [com.ice.util.FileUtils writeFile(String filePath, String content, int off, int len)]", e );
				}
			}
		}
		return false;
	}

	
	public static String readFile(File file, int len) {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			byte datas[] = new byte[len];
			bis.read(datas, 0, len);
			return new String(datas,Constants.CHAR_SET);
		} catch (Exception e) {
			logger.error ( "读取文件失败 [com.ice.util.FileUtils readFile(File file, int len )]", e );
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				logger.error ( "关闭流失败 [com.ice.util.FileUtils readFile(File file, int len )]", e );
			}
		}
		return null;
	}

	
	public static String readFile(String filePath) {
		return readFile(new File(filePath));
	}

	
	public static String readFile(File file) {
		StringBuffer content = new StringBuffer();
		if (file != null && file.exists()) {
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis, Constants.CHAR_SET);
				br = new BufferedReader(isr);
				String temp = null;
				while ((temp = br.readLine()) != null) {
					content.append(temp);
					content.append("\n");
				}
			} catch (IOException e) {
				logger.error ( "读取文件失败 [com.ice.util.FileUtils readFile(File file )]", e );
			} finally {
				try {
					if (br != null) {
						br.close();
					}
					if (isr != null) {
						isr.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					logger.error ( "关闭流失败 [com.ice.util.FileUtils readFile(File file )]", e );
				}
			}
		}
		return content.toString().trim();
	}

	
	public static List<String> readFileToList(File file) {
		List<String> lines = new ArrayList<String>();
		if (file != null && file.exists()) {
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis, Constants.CHAR_SET);
				br = new BufferedReader(isr);
				String temp = null;
				while ((temp = br.readLine()) != null) {
					lines.add(temp);
				}
			} catch (IOException e) {
				logger.error ( "读取文件失败 [com.ice.util.FileUtils readFileToList(File file )]", e );
			} finally {
				try {
					if (br != null) {
						br.close();
					}
					if (isr != null) {
						isr.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return lines;
	}
	
	/*
	public static InputStream getResourceAsStream(String resource) throws FileNotFoundException {
		String stripped = resource.startsWith("/") ? resource.substring(1) : resource;

		InputStream stream = null;
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader != null) {
			stream = classLoader.getResourceAsStream(stripped);
		}
		if (stream == null) {
			stream = Environment.class.getResourceAsStream(resource);
		}
		if (stream == null) {
			stream = Environment.class.getClassLoader().getResourceAsStream(stripped);
		}
		if (stream == null) {
			throw new FileNotFoundException(resource + " not found");
		}
		return stream;
	}
	*/
	
	public static boolean deleteFile( File file ){
		
		if( !file.exists ( ) ){
			if( logger.isInfoEnabled ( ) ){
				logger.info ( "该文件不存在" + file );
			}
			return false;
		}
		boolean delete = file.delete ( );
		
		if( logger.isInfoEnabled ( ) ){
			logger.info ( "删除文件->" + file.getName ( ) + "->" + delete  );
		}
		return delete;
	}
	
	public static boolean deleteFile( String path ){
		File file = new File( path );
		return deleteFile( file );
	}
	
	public static boolean deleteFile( String [] paths, String rootPath ){
		
		boolean isDel = false;
		
		if( rootPath == null ){
			rootPath = "";
		}
		
		if( paths == null || paths.length <= 0 ){
			return false;
		}
		
		for( int i = 0; i < paths.length; i++ ){
			String path = paths[ i ];
			isDel = deleteFile( rootPath + path );
			
			if( logger.isInfoEnabled ( ) ){
				logger.info ( "批量删除" + path + "---" + isDel );
			}
		}
		
		return isDel;
	}
	
	/**
	 * 功能描述:   
	 * 		判断文件是否存在         
	 * @param file
	 * @return
	 * @author todd benjamin  2010-1-19 上午07:17:08
	 */
	public static boolean fileExist(String file){
		return fileExist(file, false);
	}
	
	public static boolean fileExist(String path, boolean create){
		File file = new File(path);
		boolean fileExist = file.exists();
		if(create){
			if( !fileExist ){
				file.mkdirs();
			}
			fileExist = true;
		}
		
		return fileExist;
	}
	
	public static String [] filter( String path, final String regex ){
		
		File file = new File( path );
		
		if( !file.exists( ) ){
			return new String[]{};
		}
		
		String [] lists = null;
		
		if( regex == null ){
			lists = file.list ( );
		}else{
			lists = file.list( new FilenameFilter( ){
				public boolean accept( File dir, String name ) {
					return name.matches( regex );
				}
			});
		}
		
		return lists;
	}
	
	public static String [] filter( String path ){
		return filter( path, null );
	}
	
	
	
	public static File fileExistReturnFile( String path, boolean create ){
		File file = new File( path );
		boolean fileExist = file.exists ( );
		
		if( create ){
			if( !fileExist ){
				file.mkdirs ( );
				return file;
			}
		}
		
		return file;
	}
	
	public static void main ( String [ ] args ) {
		
		System.out.println ( Arrays.toString ( filter( "E:\\workspace\\fss\\WebRoot\\WEB-INF\\systemcache", "menu_\\d+.js") ) );
		
	}
}